package net.hust.atom.geotag;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class AtomGeoTagActivity extends Activity {
	
	public static final int ATOM_GEOTAG_MAP_REQUESTCODE	= 0x01;
	
	LocationManager locationManager;
	LocationListener myLocationListener;
	
	String statusChanged = "\n=== 상태 변경 : ===\n";
	String providerEnable = "\n=== 프로바이더 사용가능 : ===\n";
	String providerDisable = "\n=== 프로바이더 사용불가능 : ===\n";
	String locationChanged = "\n=== 위치 변경 : ===\n";

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String location_context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager)getSystemService(location_context);
        
//        setLocationListener();
//        getProvider();
    }
	
	public void onButton(View view){
		Toast.makeText(this, "Map Activity Start", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(this, MnMapActivity.class);
		startActivityForResult(intent, ATOM_GEOTAG_MAP_REQUESTCODE);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("ATOM", "requestCode : " + requestCode);
		Log.i("ATOM", "resultCode : " + resultCode);
	}
	
	public void getProvider(){
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.NO_REQUIREMENT);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setSpeedRequired(false);
		criteria.setCostAllowed(true);
		
		// 하나 이상일 경우 정확도가 가장 높은 것 선택
		// 없으면, 전력 사용 -> 정확도 -> 방위, 속도, 고도를 반환할 수 있는 능력 순으로 기준 완화
		// 금전 비용 기준은 암묵적으로 완화되지 않음
		String bestProvider = locationManager.getBestProvider(criteria, true);
		
		TextView tv = (TextView)findViewById(R.id.myTextView);
		StringBuilder sb = new StringBuilder("베스트 프로바이더 : ");
		
		locationManager.requestLocationUpdates(bestProvider, 1000, 0, myLocationListener);
		
		sb.append("\n").append(bestProvider).append(":");
		
		Location location = locationManager.getLastKnownLocation(bestProvider);
		if(location != null){
			double lat = location.getLatitude();
			double lng = location.getLongitude();
			sb.append(lat).append(". ").append(lng);
			Geocoder geocoder = new Geocoder(this, Locale.getDefault());
			
			List<Address> addresses = null;
			try{
				addresses = geocoder.getFromLocation(lat, lng, 5);
				int j = 1;
				for(Address address : addresses){
					Log.d("GEOTAG", "address : " + j);
					j++;
					for(int i = 0; i < address.getMaxAddressLineIndex(); i++){
						Log.d("GEOTAG", "AddressLine(" + i + ") : " + address.getAddressLine(i));
					}
					Log.d("GEOTAG", "AdminArea : " + address.getAdminArea());
					Log.d("GEOTAG", "CountryCode : " + address.getCountryCode());
					Log.d("GEOTAG", "CountryName : " + address.getCountryName());
					Log.d("GEOTAG", "FeatureName : " + address.getFeatureName());
					Log.d("GEOTAG", "Latitude : " + address.getLatitude());
					Log.d("GEOTAG", "Locality : " + address.getLocality());
					Log.d("GEOTAG", "Longitude : " + address.getLongitude());
					Log.d("GEOTAG", "Phone : " + address.getPhone());
					Log.d("GEOTAG", "PostalCode : " + address.getPostalCode());
					Log.d("GEOTAG", "Premises : " + address.getPremises());
					Log.d("GEOTAG", "SubAdminArea : " + address.getSubAdminArea());
					Log.d("GEOTAG", "SubLocality : " + address.getSubLocality());
					Log.d("GEOTAG", "SubThoroughfare : " + address.getSubThoroughfare());
					Log.d("GEOTAG", "Url : " + address.getUrl());
	
					if(address.getExtras() != null){
						for(String key : address.getExtras().keySet()){					
							Log.d("GEOTAG", "key : " + address.getExtras().get(key));
						}
					}
					Locale locale = address.getLocale();
					Log.d("GEOTAG", "locale  : " + locale.getCountry());
					Log.d("GEOTAG", "locale  : " + locale.getDisplayCountry());
					Log.d("GEOTAG", "locale  : " + locale.getDisplayLanguage());
					Log.d("GEOTAG", "locale  : " + locale.getDisplayName());
					Log.d("GEOTAG", "locale  : " + locale.getDisplayVariant());
					Log.d("GEOTAG", "locale  : " + locale.getISO3Country());
					Log.d("GEOTAG", "locale  : " + locale.getISO3Language());
					Log.d("GEOTAG", "locale  : " + locale.getLanguage());
					Log.d("GEOTAG", "locale  : " + locale.getVariant());
	//				for(Locale loc : Locale.getAvailableLocales()){
	//					Log.d("GEOTAG", "List Loc : " + loc.getDisplayName());
	//				}
	//				Log.d("GEOTAG", "Default Loc : " + Locale.getDefault().getDisplayName());
	//				for(String country : Locale.getISOCountries()){
	//					Log.d("GEOTAG", "List country : " + country);
	//				}
	//				for(String language : Locale.getISOLanguages()){
	//					Log.d("GEOTAG", "List language : " + language);
	//				}
				}
			}catch(IOException e){
				Log.e("GEOTAG", "IOException : " + e);
			}
		}else{
			sb.append("위치 없음");
		}
		
		
		tv.setText(sb);
	}
	
	private void removeLocationUpdate(){
		locationManager.removeUpdates(myLocationListener);
	}
	
	private void setLocationListener(){
		myLocationListener = new LocationListener() {
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				TextView listener1 = (TextView)findViewById(R.id.listener1);
				// 공급자 하드웨어 상태가 바뀐 경우 애플리케이션을 업데이트한다.
				Log.i("GEOTAG", "=== onStatusChanged STT ===");
				statusChanged = statusChanged + "=== onStatusChanged STT ===\n";
				Log.i("GEOTAG", "provider : " + provider);
				statusChanged = statusChanged + "provider : " + provider + "\n";
				Log.i("GEOTAG", "status : " + status);
				statusChanged = statusChanged + "status : " + status + "\n";
				for(String key :extras.keySet()){					
					Log.i("GEOTAG", "key : " + key);
					statusChanged = statusChanged + "key : " + key + "\n";
				}
				Log.i("GEOTAG", "=== onStatusChanged END ===");
				statusChanged = statusChanged + "=== onStatusChanged END ===\n";
				listener1.setText(statusChanged);
				statusChanged = "\n=== 상태 변경 : ===\n";
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// 공급자가 활성화된 경우 애플리케이션을 업데이트한다.
				TextView listener2 = (TextView)findViewById(R.id.listener2);
				Log.i("GEOTAG", "=== onProviderEnabled STT ===");
				providerEnable = providerEnable + "=== onProviderEnabled STT ===\n";
				Log.i("GEOTAG", "provider : " + provider);
				providerEnable = providerEnable + "provider : " + provider + "\n";
				Log.i("GEOTAG", "=== onProviderEnabled END ===");
				providerEnable = providerEnable + "=== onProviderEnabled END ===\n";
				listener2.setText(providerEnable);
				providerEnable = "\n=== 프로바이더 사용가능 : ===\n";
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// 공급자가 비활성화 된 경우 애플리케이션을 업데이트 한다.
				TextView listener3 = (TextView)findViewById(R.id.listener3);
				Log.i("GEOTAG", "=== onProviderDisabled STT ===");
				providerDisable = providerDisable + "=== onProviderDisabled STT ===\n";
				Log.i("GEOTAG", "provider : " + provider);
				providerDisable = providerDisable + "provider : " + provider + "\n";
				Log.i("GEOTAG", "=== onProviderDisabled END ===");
				providerDisable = providerDisable + "=== onProviderDisabled END ===\n";
				listener3.setText(providerDisable);
				providerDisable = "\n=== 프로바이더 사용불가능 : ===\n";
			}
			
			@Override
			public void onLocationChanged(Location location) {
				// 새로운 위치에 기반해 애플리케이션을 업데이트 한다.
				TextView listener4 = (TextView)findViewById(R.id.listener4);
				Log.i("GEOTAG", "=== onLocationChanged STT ===");
				locationChanged = locationChanged + "=== onLocationChanged STT ===\n";
				if(location.hasAccuracy()){
					Log.i("GEOTAG", "Accuracy : " + location.getAccuracy());
					locationChanged = locationChanged + "Accuracy : " + location.getAccuracy() + "\n";
				}
				if(location.hasAltitude()){
					Log.i("GEOTAG", "Altitude : " + location.getAltitude());
					locationChanged = locationChanged + "Altitude : " + location.getAltitude() + "\n";
				}
				if(location.hasBearing()){
					Log.i("GEOTAG", "Bearing : " + location.getBearing());
					locationChanged = locationChanged + "Bearing : " + location.getBearing() + "\n";
				}
				if(location.hasSpeed()){
					Log.i("GEOTAG", "Speed : " + location.getSpeed());
					locationChanged = locationChanged + "Speed : " + location.getSpeed() + "\n";
				}
				
				Log.i("GEOTAG", "Latitude : " + location.getLatitude());
				locationChanged = locationChanged + "Latitude : " + location.getLatitude() + "\n";
				Log.i("GEOTAG", "Longitude : " + location.getLongitude());
				locationChanged = locationChanged + "Longitude : " + location.getLongitude() + "\n";
				Log.i("GEOTAG", "Provider : " + location.getProvider());
				locationChanged = locationChanged + "Provider : " + location.getProvider() + "\n";
				Log.i("GEOTAG", "Time : " + location.getTime());
				locationChanged = locationChanged + "Time : " + location.getTime() + "\n";
				
				for(String key :location.getExtras().keySet()){					
					Log.i("GEOTAG", "key : " + key);
					locationChanged = locationChanged + "key : " + key + "\n";
					locationChanged = locationChanged + "key Object : " + location.getExtras().get(key) + "\n";
				}
				Log.i("GEOTAG", "=== onLocationChanged END ===");
				locationChanged = locationChanged + "=== onLocationChanged END ===\n";
				listener4.setText(locationChanged);
				locationChanged = "\n=== 위치 변경 : ===\n";
			}
		};
	}
}